﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Web.Libs
{
    public class AliyunSmsHelper
    {
        public static string product = "Dysmsapi"; //短信API产品名称
        public static string domain = "dysmsapi.aliyuncs.com"; //短信API产品域名
        public static string accessKeyId = "LTAIJ7KIvnRj6XnO"; //accessKeyId
        public static string accessKeySecret = "S7TK4xF7vXlxSqvuZoDfGHYE699XlJ"; //accessKeySecret
        public static string signName = "阿里云短信测试专用";  //短信签名-可在短信控制台中找到
        public static string templateCode = "SMS_112815070"; //短信模板-可在短信控制台中找到
        public static string outId = "yourOutId";  //outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者

        /// <summary>
        /// 发送验证码
        /// </summary>
        /// <param name="mobile">接受者手机号码</param>
        /// <param name="code">验证码</param>
        public static bool SendCode(string mobile, string code)
        {
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            try
            {
                request.PhoneNumbers = mobile;
                request.SignName = signName;
                request.TemplateCode = templateCode;
                request.TemplateParam = "{\"code\":\"" + code + "\"}";
                request.OutId = outId;
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                return sendSmsResponse.Code == "OK";
            }
            catch (ServerException e)
            {
                return false;
            }
            catch (ClientException e)
            {
                return false;
            }
        }
    }
}